package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.dto.SeeRecordGoodsCountRequest;
import com.jmp.base.dto.SunCodeGoodsRequest;
import com.jmp.base.dto.SunCodeGoodsResponse;
import com.jmp.feign.SeeRecordFeign;
import com.jmp.feign.SunCodeFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.*;
import one.stand.enums.SeeRecordEnums;
import one.stand.mapper.GoodsApiShowroomMapper;
import one.stand.mapper.SeeRecordPublicMapper;
import one.stand.model.*;
import one.stand.service.CompanyShowroomService;
import one.stand.service.GoodsBaseService;
import one.stand.service.GoodsPhotoService;
import one.stand.service.GoodsTypeService;
import one.stand.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Api(description = "商品")
@RestController
@RequestMapping("goods")
public class GoodsController {
    @Autowired
    private GoodsApiShowroomMapper goodsApiShowroomMapper;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private CompanyShowroomService companyShowroomService;
    @Autowired
    private SeeRecordPublicMapper seeRecordPublicMapper;
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private SeeRecordFeign seeRecordFeign;
    @Autowired
    private SunCodeFeign sunCodeFeign;

    @ApiOperation("商城-商品列表")
    @PostMapping("search")
    @SecurityAuthCheck(company = true)
    public ResultModel<GoodsSearchResponse> search(@RequestBody GoodsSearchRequest request) {
        final Integer companyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();
        final String keyword = SqlUtil.like(request.getKeyword());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Goods> goodsModels = goodsApiShowroomMapper.selectSearch(companyId, keyword, request.getCategoryId());

        PageResponse2<GoodsSearchResponse.Goods> goodss = ConvertUtils.page2(goodsModels, model -> {
            boolean isPay = model.getShowPrice() == 1;//1 显示价格
            GoodsType goodsType = goodsTypeService.get(model.getGoodstypeId());
            String categoryName = goodsType.getGroupName().split(GoodsTypeService.SPLIT)[0];
            return GoodsSearchResponse.Goods.builder()
                    .id(model.getGoodsId())
                    .name(model.getGoodsName())
                    .price(PriceUtil.getPriceView2(isPay, model.getPrice()))
                    .path(goodsPhotoService.getPath(model.getGoodsId()))
                    .visitNum(seeRecordPublicMapper.selectCount(SeeRecordEnums.PRODUCT.getCode(), model.getGoodsId()))
                    .categoryName(categoryName)
                    .categoryName2(goodsType.getName())
                    .hasVr(StringUtils.isNoneBlank(model.getQjVrUrl()))
                    .hasVideo(StringUtils.isNoneBlank(model.getVideoUrl()))
                    .hasAr(goodsBaseService.hasAr(model.getGoodsId()))
                    .build();
        });

        GoodsSearchResponse response = GoodsSearchResponse.builder()
                .goodsList(goodss)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("商城-商品详情")
    @PostMapping("detail")
    @SecurityAuthCheck(company = true)
    public ResultModel<GoodsDetailResponse> detail(@RequestBody GoodsDetailRequest request) {
        final Integer companyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();
        Goods goodsModel = goodsBaseService.getOn(request.getId());
        Assert.notNull(goodsModel, "商品不存在或已下架");
        Assert.isTrue(companyId.equals(goodsModel.getCompanyId()), "无权查看此商品");
        List<String> pics = goodsPhotoService.getListPath(request.getId());
//        BigDecimal price = goodsBaseService.getPrice(request.getId());
        final boolean isPay = goodsModel.getShowPrice() == 1;//1 显示价格
        String priceDetail = null;

        List<GoodSpec> specModels = goodsBaseService.getSpecs(request.getId());

        //规格
        List<GoodsDetailResponse.Type> types = Lists.newArrayList();
        if (OneListUtil.isNotEmpty(specModels)) {
            GoodsDetailResponse.Type type = null;
            GoodsDetailResponse.Sku sku;
            String price;
            for (GoodSpec specModel : specModels) {
                if (Objects.nonNull(specModel.getParentId()) && specModel.getParentId() == 0) {
                    if (Objects.nonNull(type)) {
                        types.add(type);
                    }
                    type = GoodsDetailResponse.Type.builder()
                            .name(specModel.getSpecName())
                            .content(Lists.newArrayList())
                            .build();
                } else if (Objects.nonNull(type)) {
                    BigDecimal specPrice = Objects.nonNull(specModel.getPriceRemark()) ? specModel.getPriceRemark() : MoneyUtil.getMoney(specModel.getPrice());
                    price = PriceUtil.getPriceView(isPay, specPrice);

                    if (Objects.isNull(priceDetail)) {
                        priceDetail = price;
                    }

                    sku = GoodsDetailResponse.Sku.builder()
                            .name(specModel.getSpecAttribute())
                            .price(price)
                            .build();
                    type.getContent().add(sku);
                }
            }
            if (Objects.nonNull(type)) {
                types.add(type);
            }
        }

        final Integer cardId = RequestContextHolder.getRequestContext().getUser().getCardId();

        CompanyShowroom companyShowroom = companyShowroomService.getByCompanyId(goodsModel.getCompanyId());
        String suncode;
        if (Objects.nonNull(companyShowroom) && CompanyShowroomService.SHOW_CODE_OFF == companyShowroom.getShowCode()) {
            suncode = null;
        } else {
            SunCodeGoodsRequest sunCodeGoodsRequest = SunCodeGoodsRequest.builder()
                    .specId(specModels.get(0).getSpecId())
                    .cardId(cardId)
                    .build();
            ResultModel<SunCodeGoodsResponse> sunCodeGoodsResponseResultModel = sunCodeFeign.goods(sunCodeGoodsRequest);//分享码
            AssertUtil.isTrue(sunCodeGoodsResponseResultModel);
            suncode = sunCodeGoodsResponseResultModel.getData().getCodeUrl();
        }

        seeRecordFeign.goodsCount(SeeRecordGoodsCountRequest.builder().goodsId(goodsModel.getGoodsId()).build());

        GoodsDetailResponse response = GoodsDetailResponse.builder()
                .id(goodsModel.getGoodsId())
                .name(goodsModel.getGoodsName())
                .description(goodsModel.getGoodsName()) // TODO: 2019/6/22 商品描述暂无，先使用商品名称
                .types(types)
                .detail(goodsModel.getGoodsDetails())
                .vrUrl(goodsModel.getQjVrUrl())
                .pics(pics)
                .price(priceDetail)
                .sunCode(suncode)
                .videoUrl(goodsModel.getVideoUrl())
                .build();
        return ResultModel.success(response);
    }
}
